// 数据库增删改查的封装
module.exports = {
    // 增
    insert(collection, insertDate) {
        // collection.insertMany(insertDate);
        return new Promise((resolve, reject) => {
            collection.insertMany(insertDate, (err) => {
                if (err) {
                    reject(err)
                } else {
                    resolve("插入成功");
                };
            });
        })
    },
    // 删
    delete(collection, whereDate, num) {
        // collection.deleteOne()
        // collection.deleteMany()
        const dataType = num && num === 1 ? "deleteMany" : "deleteOne";
        return new Promise((resolve, reject) => {
            collection[dataType](whereDate, (err) => {
                if (err) {
                    reject(err)
                } else {
                    resolve("删除成功");
                };
            })
        })
    },
    // 改
    update(collection, whereDate, setDate, num) {
        // collection.updateOne()
        // collection.updateMany()
        const dataType = num && num === 1 ? "updateMany" : "updateOne";
        return new Promise((resolve, reject) => {
            collection[dataType](whereDate, setDate, (err) => {
                if (err) {
                    reject(err)
                } else {
                    resolve("修改成功");
                };
            })
        })
    },
    // 查
    find(collection, whereDate, showDate) {
        return new Promise((resolve, reject) => {
            collection.find(whereDate, showDate, (err, data) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(data);
                };
            })
        })
    },
    // 排序
    sort(collection, whereDate, showDate, sortDate) {
        return new Promise((resolve, reject) => {
            collection.find(whereDate, showDate).sort(sortDate).exec((err, data) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(data);
                };
            })
        })
    },
    // 分页
    page(collection, whereDate, showDate, limit, count) {
        return new Promise((resolve, reject) => {
            collection.find(whereDate, showDate).limit(limit).skip((count - 1) * limit).exec((err, data) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(data);
                };
            })
        })
    },
    // 查询字段名所有值（去重后）
    distinct(collection, type) {
        return new Promise((resolve, reject) => {
            collection.distinct(type, (err, data) => {
                if (err) {
                    reject(err)
                } else {
                    resolve(data);
                };
            })
        })
    }
}